#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;

int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
    int row = entrance.front();
    int col = entrance.back();
    int ret = bfs(maze, row, col);
    return ret;
}

int bfs(vector<vector<char>>& v, int a, int b)
{
    int x_[4] = { 0,0,-1,1 };
    int y_[4] = { 1,-1,0,0 };
    int count = 0;

    queue<pair<int, int>> q;
    q.push({ a,b });
    v[a][b] = '+';

    while (q.size())
    {
        int sz = q.size();
        count++;
        for (int i = 0; i < sz; i++)
        {
            int m = q.front().first;
            int n = q.front().second;
            q.pop();

            for (int j = 0; j < 4; j++)
            {
                int x = m + x_[j];
                int y = n + y_[j];
                if (x >= 0 && y >= 0 && x < v.size() && y < v[0].size() && v[x][y] == '.')
                {
                    if (x == 0 || y == 0 || x == v.size() - 1 || y == v[0].size() - 1)
                    {
                        return count;
                    }
                    q.push({ x,y });
                    v[x][y] = '+';
                }
            }
        }
    }
    return -1;
}